package com.wl.shop.web;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wl.shop.entity.Role;
import com.wl.shop.entity.User;
import com.wl.shop.model.DataTableResult;
import com.wl.shop.model.RestResponse;
import com.wl.shop.model.UserVO;
import com.wl.shop.utils.Constants;
import com.wl.shop.utils.DateUtils;
import com.wl.shop.utils.StringUtils;

@Controller
@RequestMapping("${adminPath}/user")
public class UserController extends BaseController {
	
	@RequestMapping(value = "list",method=RequestMethod.GET)
	public String list(Model model){
		logger.info("跳转用户列表---");
		return "sys/user/list";
	}
	
	@RequestMapping(value = "list",method=RequestMethod.POST)
	@ResponseBody
	public DataTableResult list(String aodata,ServletRequest request){
		Map<String,Object>	map =Constants.convertToMap(aodata);
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		int echo = (Integer) map.get("sEcho");
		int start = (Integer)map.get("iDisplayStart");
		int pageSize = (Integer)map.get("iDisplayLength");
		int pageNum = start/pageSize==0?1:(start/pageSize+1);
		DataTableResult result = new DataTableResult();
		result.setSEcho(echo);
		EntityWrapper<User> wrapper = new EntityWrapper<User>();
		wrapper.eq("is_del", false);
		Page<User> page  =userService.listByParam(new Page<User>(pageNum,pageSize), searchParams);
		result.setAaData(page.getRecords());
		result.setITotalRecords(page.getTotal());
		result.setITotalDisplayRecords(page.getTotal());
		if(!searchParams.isEmpty()){
			result.setSColumns(Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		}
		return result;
	}
	
	public List<User> addRoleNameToUser(List<User> userList){
		for (User user : userList) {
			List<String>  roleIds = userRoleService.getRoleIdsByUserId(user.getId());
			List<Role> roleList = Lists.newArrayList();
			for (String roleId : roleIds) {
				Role r = roleService.selectById(roleId);
				roleList.add(r);
			}
			user.setRoleList(roleList);
		}
		return userList;
	}
	
	@RequestMapping(value = "add",method = RequestMethod.GET)
	public String add(Model model){
		EntityWrapper<Role> wrapper = new EntityWrapper<Role>();
		wrapper.eq("is_del", false);
		List<Role> list = roleService.listByParam(wrapper);
		model.addAttribute("roleList", list);
		return "sys/user/add";
	}
	
	@RequestMapping(value = "add",method = RequestMethod.POST)
	@ResponseBody
	public RestResponse add(@RequestBody UserVO user){
		if(StringUtils.isBlank(user.getLoginName())){
			return RestResponse.failure("登陆账号不能为空");
		}
		if(StringUtils.isBlank(user.getPassword())){
			return RestResponse.failure("密码不能为空");
		}
		List<String> roleIds = user.getRoleIds();
		if(roleIds == null || roleIds.size() == 0){
			return RestResponse.failure("用户角色未选择");
		}
		EntityWrapper<User> wrapper = new EntityWrapper<User>();
		wrapper.eq("is_del", true).eq("login_name", user.getLoginName());
		List<User>  userList = userService.selectList(wrapper);
		if(userList.size()>0){
			return RestResponse.failure("登录名已被使用");
		}
		User sysuser = new User();
		sysuser.setLoginName(user.getLoginName());
		sysuser.setName(user.getName());
		sysuser.setMobile(user.getMobile());
		sysuser.setPassword(user.getPassword());
		sysuser.setEmail(user.getEmail());
		sysuser.setRemarks(user.getRemarks());
		userService.saveOrUpdate(sysuser);
		if(StringUtils.isNotBlank(sysuser.getId())){
			userRoleService.saveUserRole(sysuser.getId(), StringUtils.join(roleIds, ","));
		}
		return RestResponse.success();
	}

	@RequestMapping(value = "edit",method = RequestMethod.GET)
	public String edit(String id,Model model){
		EntityWrapper<Role> wrapper = new EntityWrapper<Role>();
		wrapper.eq("is_del", false);
		List<Role> list = roleService.listByParam(wrapper);
		model.addAttribute("roleList", list);
		
		User user = userService.selectById(id);
		model.addAttribute("user", user);
		
		List<String> roleIds = userRoleService.getRoleIdsByUserId(id);
		model.addAttribute("roleIds", StringUtils.join(roleIds, ","));
		return "sys/user/edit";
	}
	
	@RequestMapping(value = "edit",method = RequestMethod.POST)
	@ResponseBody
	public RestResponse edit(@RequestBody UserVO user){
		if(StringUtils.isBlank(user.getId())){
			return RestResponse.failure("用户ID不能为空");
		}
		if(StringUtils.isBlank(user.getLoginName())){
			return RestResponse.failure("登陆账号不能为空");
		}
		List<String> roleIds = user.getRoleIds();
		if(roleIds == null || roleIds.size() == 0){
			return RestResponse.failure("用户角色未选择");
		}
		User old = userService.selectById(user.getId());
		if(!old.getLoginName().equals(user.getLoginName())){
			return RestResponse.failure("登录名不能被修改");
		}
		User sysuser = new User();
		sysuser.setId(user.getId());
		sysuser.setName(user.getName());
		sysuser.setMobile(user.getMobile());
		if(StringUtils.isNotBlank(user.getPassword())){
			sysuser.setPassword(user.getPassword());
		}
		sysuser.setEmail(user.getEmail());
		sysuser.setRemarks(user.getRemarks());
		userService.saveOrUpdate(sysuser);
		if(StringUtils.isNotBlank(sysuser.getId())){
			userRoleService.saveUserRole(sysuser.getId(), StringUtils.join(roleIds, ","));
		}
		return RestResponse.success();
	}
	
	@RequestMapping(value = "delete",method = RequestMethod.POST)
	@ResponseBody
	public RestResponse delete(@RequestParam(value = "id[]",required = false)List<String> id){
		if(id == null || id.size() == 0){
			return RestResponse.failure("用户ID不能为空");
		}
		for (String userId : id) {
			if("1".equals(userId)){
				return RestResponse.failure("超级管理员不能删除");
			}
			User user = userService.selectById(userId);
			if(user == null){
				return RestResponse.failure("数据出错");
			}
			user.setIsDel(true);
			userService.saveOrUpdate(user);
			Map<String, Object> map = Maps.newHashMap();
			map.put("user_id", userId);
			userRoleService.deleteByMap(map);
		}
		return RestResponse.success();
	}
}
